package ar.org.cfired.parametros;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jbpm.api.Configuration;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.NewDeployment;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Task;

public class DeployParametros {
	public static void main(String[] args) {
		NewDeployment deployment = new Configuration().buildProcessEngine().getRepositoryService().createDeployment();
		deployment.addResourceFromClasspath("ar/org/cfired/creditos/parametros/crearInstancia.jpdl.xml");
		deployment.addResourceFromClasspath("ar/org/cfired/creditos/parametros/crearInstancia.png");
		
		deployment.setName("Crear Instancia - 2011-12-12 - v1.0.3 beta rel 2");
		deployment.setTimestamp(new Date().getTime());
		deployment.deploy(); 
		
		System.out.println("Deploy hecho"); 
		
        //ExecutionService executionSe = new Configuration().buildProcessEngine().getExecutionService();
        
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("graNumeroCuenta", "Crear Instancia Creditos");
       
		
		
		
        ProcessEngine pe =  new Configuration().buildProcessEngine();
        ExecutionService executionService = pe.getExecutionService();
        ProcessInstance processInstance = null;
        processInstance = executionService.startProcessInstanceByKey("crear_instancia", variables);
        
        
		SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure("hib.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
        
		TaskService taskService = pe.getTaskService();
		List<Task> lista = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
		String id_tarea;
		if (lista.size()>0)
			id_tarea = lista.get(0).getId();
		else
			id_tarea = "0";
		Query q = session.createSQLQuery("insert into jbpmCreditos.dbo.sec_parametro values ('Crear Instancia', " + id_tarea + ")" );
		int afectados = q.executeUpdate();
		
		System.out.println("Afectados: " + afectados);
		
		session.getTransaction().commit();

        System.out.println(processInstance.getState());		
	}
}
